package com.ic.service.impl;

import com.ic.config.OssUtil2;
import com.ic.domain.Age;
import com.ic.domain.FaceDetectionResult;
import com.ic.domain.dto.FaceRecognitionDTO;
import com.ic.domain.response.FaceDetectionResponse;
import com.ic.remote.RemoteToWebsocket;
import com.ic.remote.RemoteTofaceservice;
import com.ic.service.DataingressService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Log4j2
public class DataingressServiceImpl implements DataingressService {
//测试
    @Autowired
    private OssUtil2 ossUtil2;

    @Autowired
    private RemoteTofaceservice dataingressTofaceservice;

    @Autowired
    private KafkaTemplate<Object, Object> kafkaTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RemoteToWebsocket remote;


    @Override
    public void access(FaceRecognitionDTO data) {
        log.info("开始处理数据接入请求: {}", data);

        try {
//            远程调用人脸识别算法 获取人基本信息
            FaceDetectionResponse response = dataingressTofaceservice.recognizeFaceContrast(data.getImage()).getData();
            List<FaceDetectionResult> results = response.getResult();
            log.debug("面部检测结果: {}", results);
            String imageUrl = ossUtil2.base64ToOssUrl(data.getImage());
            for (FaceDetectionResult result : results) {
                FaceRecognitionDTO dto = new FaceRecognitionDTO();
                dto.setMask(result.getMask().getValue());
                Age age = result.getAge();
                dto.setMinage(age.getLow());
                dto.setMaxage(age.getHigh());
                dto.setGender(result.getGender().getValue());
                dto.setImage(imageUrl);
                dto.setDate(new Date());
//                将消息推送kafka
                kafkaTemplate.send("data", dto);
            }
            // 使用Redis原子性操作增加成功计数器
            int incrementAmount = results.size();
//         计数共有多少照片
            ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
            opsForValue.increment("faceRecognitionSuccessCount", incrementAmount);
            log.info("数据接入请求处理成功，成功处理 {} 张面部", incrementAmount);
        } catch (Exception e) {
            log.error("数据接入请求处理失败: {}", data, e);
            throw new RuntimeException("处理数据接入请求时发生错误", e);
        }
    }

    @Override
    public void compareFaces(FaceRecognitionDTO data) {
        access(data);
        FaceDetectionResponse response = dataingressTofaceservice.recognizeFaceContrast(data.getImage()).getData();
        List<FaceDetectionResult> results = response.getResult();
        log.debug("面部检测结果: {}", results);
        Timestamp timestamp = new Timestamp(new Date().getTime());
        String imageUrl = ossUtil2.base64ToOssUrl(data.getImage());
        for (FaceDetectionResult result : results) {
            FaceRecognitionDTO dto = new FaceRecognitionDTO();
            dto.setMask(result.getMask().getValue());
            Age age = result.getAge();
            dto.setMinage(age.getLow());
            dto.setMaxage(age.getHigh());
            dto.setGender(result.getGender().getValue());
            dto.setImage(imageUrl);
            dto.setDate(timestamp);
            dto.setId(UUID.randomUUID().toString());
            kafkaTemplate.send("comparisons", dto);
        }
    }

    // 新增方法：获取成功计数器的当前值

    public long getFaceRecognitionSuccessCount() {
        return stringRedisTemplate.opsForValue().increment("faceRecognitionSuccessCount", 0);
    }

    // 新增方法：重置成功计数器的值
    public void resetFaceRecognitionSuccessCount() {
        stringRedisTemplate.delete("faceRecognitionSuccessCount");
    }

    // 新增方法：设置成功计数器的过期时间
    public void setFaceRecognitionSuccessCountExpireTime(long timeout, TimeUnit unit) {
        stringRedisTemplate.expire("faceRecognitionSuccessCount", timeout, unit);
    }

}
